package client.service;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.InputStream;

/**
 * netty Client
 */

public class TestClient {

    public static void main(String[] args) {
        TestClient testClient = new TestClient();
        testClient.connectServer("localhost",8180);
    }

    public void connectServer(String host,int port){

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            //配置Channel
            b.group(group).channel(NioSocketChannel.class)
                    //设置通道选项  有数据立即发送
                   .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new CustomChannelHandler());

            //对服务端发起链接请求---
            ChannelFuture connect = b.connect(host, port).sync();
            System.out.println("客户端发起链接请求");
            //等待客户端链接关闭 -- 线程在此处阻塞
            connect.channel().closeFuture().sync();
            System.out.println("客户端开始关闭---");
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("客户端启动出现异常!");
        }finally{
            //关闭线程释放资源
            group.shutdownGracefully();
            System.out.println("客户端已关闭!");
        }

    }
}
